package com.qss.workutil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qss.util.cin_txt;

//常用方法
//getContentMiddleDeal01(
//workPath(
//void workPath()
//dealContent(){

/*
 说明：执行的时候，分两种情况，后缀为 </s:select>  和  />
 ADP 搜索情况
 	<s:select 	252个匹配
   	</s:select>	183个匹配
   	/>			 69
   	没有办法直接搜索，替换完</s:select>后，再搜索<s:select就是情况2的数量
 	
 ADS 搜索情况
   <s:select 	196个匹配
   </s:select>	147个匹配
   />			 49个匹配
       没有办法直接搜索，替换完</s:select>后，再搜索<s:select就是情况2的数量

情况1
<s:select id="entity_certType" name="entity.certType" 
	list="certTypeList" listKey="itemCode" listValue="itemName" 
	headerKey="" headerValue="请选择" 
	cssClass="required" validate="{required:true}" ></s:select>
	
情况2
<s:select id="entity_custId"  name="entity.custId" 
	list="rescueDefendantList" listKey="id" listValue="itemName"
	headerKey="" headerValue="--请选择--"  />
	 
*/
public class Test2Dict {
	private static final Logger logger=LoggerFactory.getLogger(Test2Dict.class);
	public static Map<String,String> dictMap = new HashMap<String,String>();
	
	/**经常修改-start*/
	//11-单个文件(处理，写到文件中)  12-单个文件(处理，不 写到文件中)	  13-单个文件(不 处理，不 写到文件中)
	//21-循环文件(处理，写到文件中)  22-循环文件(处理，不 写到文件中)  23-循环文件(不 处理，不 写到文件中)
	//99-全部文件匹配个数(不 处理，不 写到文件中)，只是输出每个文件的匹配个数
	public static final int  workType_ALL_FILE = 99;
	public static int 	 workType = 22;			
	
	//1-字典
	public static int 	 singleOrDouble = 1;	
	
	public static String matchContent = ""; 	//查找内容
	public static String singleMatchContent = "<s:select"; 
	
	//单个文件
	public static String subStrPrefix =  "<s:select"; 	//截取字符串前缀  <div	<td
	//后缀动态判断
	public static String subStrPostfix = "</s:select>";	//截取字符串后缀
//	public static String subStrPostfix = "/>";			//截取字符串后缀
	
	public static boolean isPrintTsLog = false;		//是否打印调试日志
	public static boolean printGeShu = true; 		//是否打印出每个页面的个数
	/**经常修改-end*/
	
	//项目
	public static String projectAds = "ads";		
	public static String projectCrms = "crms";		
	public static String projectAdp = "adp";		
	public static String projectStr = projectAdp;
	
	//workPath-文件夹 
	public static String filePath = ""; 
	public static String filePathAds 	= "C:\\workspaces\\ads1\\ads-web\\src\\main\\webapp\\pages\\ads";
	public static String filePathCrms	= "C:\\workspaces\\crms2\\crms-web\\src\\main\\webapp\\pages\\crms";
	public static String filePathAdp 	= "C:\\workspaces\\adp\\adp-web\\src\\main\\webapp\\pages\\adp";
	public static String filePathAdsAction 	= "C:\\workspaces\\ads1\\ads\\src\\main\\java\\com\\yinker\\ads";
	
	//偶尔修改  /gc/GcLoanCreditQueryInfo/list.jsp
	//single
	//crms-qk1 \gc\GcBackBorkerInfo\queryBackBorkerList.jsp
	public static String fileName1 = "/lmt/LmtFlowAdvanceUpperCheck/_edit_new"+".jsp";
	public static String fileName2 = "/lmt/LmtFlowAdvanceUpperCheck/_edit_new"+"2.jsp";
	
	public static boolean isDealFile = true; 		//是否处理文件
	public static boolean isWriteToFile = true; 	//是否将修改后的内容，写入文件中
	
	//几乎不修改
	//searchFile
	public static int fileCount = 0;  //文件数量（一个文件里面包含至少0个 修改数量）
	public static int modifyCount = 0;//修改数量（应该和 匹配次数 相等）
	public static int matchCount = 0; //匹配数量
	public static int successCount = 0; //成功数量
	public static int geshu = 0;//文件里面包含的双日历个数
	public static String contentStr = "";//文件内容
	
//	public static Map errorMap = new HashMap();
	public static Set<String> errorSet = new HashSet<String>();
	public static int errorCounter = 0;
	
	/**
	 * main方法
	 */
	public static void main(String[] args) throws Exception {
		init();
		logger.info("二、业务操作");
		if(workType==11){
			isDealFile = true;
			isWriteToFile = true;
			single();
		}else if(workType==12){
			isDealFile = true;
			isWriteToFile = false;
			single();
		}else if(workType==13){
			isDealFile = false;
			isWriteToFile = false;
			single();
		}else if(workType==21){
			isDealFile = true;
			isWriteToFile = true;
			workPath();
		}else if(workType==22){
			isDealFile = true;
			isWriteToFile = false;
			workPath();
		}else if(workType==23){
			isDealFile = false;
			isWriteToFile = false;
			workPath();
		}else if(workType==workType_ALL_FILE){
			isDealFile = false;
			isWriteToFile = false;
			workPath();
		}
		
		logger.info("");
		end();
	}
	
	public static void init() throws IOException{
		logger.info("");
		logger.info("");
		logger.error("一、TestDict初始化操作");
		logger.info("Now:{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		//singleOrDouble = 1;			//1-single    2-double
		if(singleOrDouble==1){
			matchContent = singleMatchContent;
		}
		
		String projectName = "";
		if(projectStr.equals(projectAds)){
			filePath = filePathAds;
			projectName = projectAds;
		}else if(projectStr.equals(projectCrms)){
			filePath = filePathCrms;
			projectName = projectCrms;
		}else if(projectStr.equals(projectAdp)){
			filePath = filePathAdp;
			projectName = projectAdp;
		}
		fileName1 = filePath+fileName1;
		fileName2 = filePath+fileName2;
		
		logger.info("项目名称-->"+projectName);
		logger.info("workType-->"+workType);
		logger.info("singleOrDouble-->"+singleOrDouble);
		logger.info("查询内容matchContent-->"+matchContent);
		logger.info("文件夹filePath-->"+filePath);
		
		if(workType==1){
			logger.info("文件夹fileName1-->"+fileName1);
			logger.info("文件夹fileName2-->"+fileName2);
		}
		
		if(singleOrDouble==1){
			logger.info("调用的方法-->getContentMiddleDeal01");
		}else if(singleOrDouble==2 || singleOrDouble==21 ){
			logger.info("调用的方法-->getContentMiddleDeal02");
		}
		
		//list="collClassOneList"
		//得到list对应的字典code
//		try {
//			Test2DictAction.run();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		logger.error("qss123");
		dictMap = cin_txt.readFile();
		
		logger.info("");
	}
	
	public static void end(){
		logger.info("三、结束操作");
		logger.info("错误文件数量为----------------->"+errorSet.size());
		if(errorSet.size()>0){
			for(String str:errorSet){
				logger.info("qss1-->"+str);
			}
			logger.info("错误文件数量为----------------->"+errorSet.size());
		}
		logger.info("成功数量-successCount---------->"+successCount);
		logger.info("整体循环数量-modifyCount------->"+modifyCount);
		
		if(singleOrDouble==1){
			logger.info("总数量（匹配数量）-matchCount-->"+matchCount);
		}else if(singleOrDouble==2){
			logger.info("总数量（匹配数量）-matchCount-->"+matchCount/2);
		}
		
		logger.info("搜索文件数量-fileCount--------->"+fileCount);
        
		logger.info("");
		logger.info("=============执行完毕=============");
		logger.info("Now:{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		logger.info("");
		logger.info("");
		logger.info("");
		logger.info("");
		
		System.exit(0);
	}
	
	/**
	 * 单日历
	 * 得到处理内容：处理后的内容。
	 * @param content
	 * @return
	 */
	public static String getContentMiddleDeal01(String dealContent){
		logger.info("		getContentMiddleDeal01--方法--start");
		logger.info("		处理前的内容--dealContent-->");
		logger.info(dealContent);
		String returnContentMiddle = "";
		boolean dealStatus = false;
		
		String dateMatchPrefix 	= "";
		String dateMatchPostfix = "";
		
		if(dealContent.contains("qsssss")){
			errorSet.add(fileCount+"--"+"qsssss"+fileName1);
			
		}else{
			successCount++;
			String var1 = getValueByAttribute(dealContent,"name=\"");
			String var2 = getValueByAttribute(dealContent,"list=\"");
			String var2Temp = var2.toLowerCase();
			if(var2Temp.contains("province") ){
				errorSet.add(fileCount+"--"+"包含 province "+fileName1);
				return dealContent.replace("<s:select", "<s2:select").replace("</s:select>", "</s2:select>");
			}else if(var2Temp.contains("city") ){
				errorSet.add(fileCount+"--"+"包含 city     "+fileName1);
				return dealContent.replace("<s:select", "<s2:select").replace("</s:select>", "</s2:select>");
			}else if(var2Temp.contains("area") ){
				errorSet.add(fileCount+"--"+"包含 area    "+fileName1);
				return dealContent.replace("<s:select", "<s2:select").replace("</s:select>", "</s2:select>");
			}
			
			String var3 = getValueByPrefix(dealContent, "id=\"", "\"");
			String var4 = dealContent.contains("true")?"1":"0";
			String var5 = getValueByAttribute(dealContent,"listKey=\"");
			String var6 = getValueByAttribute(dealContent,"listValue=\"");
			
			if(isPrintTsLog){
				logger.info("var1-->"+var1);
				logger.info("var2-->"+var2);
				logger.info("var3-->"+var3);
				logger.info("var4-->"+var4);
				logger.info("var5-->"+var5);
				logger.info("var6-->"+var6);
			}
			
			/*
			 <z:select name="queryEntity.status" 
				list="status" listKey="itemCode" listValue="itemName" 
				opennerRel="%{#parameters.zwork_ui_rel}" id="entity_busiModel" 
				useScene="select"	minSelectNodeNumber="1"		
				selectStyle="radio" tooltip="请选择"/>
			 */
			StringBuffer strBuf = new StringBuffer();
			String blanks = "";
			if(fileName1.toLowerCase().contains("list.jsp")
					|| fileName1.toLowerCase().contains("view.jsp")
					|| fileName1.toLowerCase().contains("info.jsp") ){
				blanks = "						"; //6个tab
			}
			
			strBuf.append("<z:select name=\"var1\" 										\r\n");
			strBuf.append(blanks+"			list=\"var2\" listKey=\"var5\" listValue=\"var6\" 	\r\n");
			strBuf.append(blanks+"			opennerRel=\"%{#parameters.zwork_ui_rel}\" var3				\r\n");
			strBuf.append(blanks+"			useScene=\"select\"	minSelectNodeNumber=\"var4\"			\r\n");
			strBuf.append(blanks+"			selectStyle=\"radio\" tooltip=\"请选择\"/>					\r\n");
			
			returnContentMiddle = strBuf.toString();
			returnContentMiddle = returnContentMiddle
					.replace("var1", var1).replace("var2", var2)
					.replace("var3", var3).replace("var4", var4)
					.replace("var5", var5).replace("var6", var6);
			
			logger.info("");
			logger.info("		处理后的内容--returnContentMiddle-->");
			logger.info(returnContentMiddle);
			
			dealStatus = true;
		}
		
		logger.info("		本次处理结果-->"+dealStatus);
		logger.info("		getContentMiddleDeal01--方法--end");
		
		return returnContentMiddle;
	}
	
	/**
	 * 通过属性得到值。  
	 * 如：name="queryEntity.dealDateStart"
	 * 通过  name="  得到  queryEntity.dealDateStart
	 */
	public static String getValueByAttribute(String content,String prefix){
		if(content.contains(prefix)){
			return getValueByAttribute(content, prefix, "\"", true);
		}else{
			return "";
		}
	}
	
	/**
	 * 通过属性得到值。  
	 * 如：name="queryEntity.dealDateStart"
	 * 通过  name="  得到  queryEntity.dealDateStart
	 * direction：true正向第一个  false反向第一个
	 */
	public static String getValueByAttribute(String content,String prefix,String postfix,boolean direction){
		int indexTemp41 = 0;
		if(direction){
			indexTemp41 = content.indexOf(prefix);
		}else{
			indexTemp41 = content.lastIndexOf(prefix);
		}
		String varTemp = content.substring(indexTemp41+prefix.length());
		
		int indexTemp42 = varTemp.indexOf(postfix);
		varTemp = varTemp.substring(0, indexTemp42);
		
		return varTemp;
	}
	
	/**
	 * <div class="row2 slgj"></div> <label for="entity1_endTime">竣工时间</label>
	 * 通过  <div 和   </div>，得到 <div class="row2 slgj"></div>
	 */
	public static String getValueByPrefix(String content,String prefix,String postfix){
		if(content.contains(prefix)&&content.contains(postfix)){
			String str1Middle = getValueByAttribute(content,prefix,postfix,true);
			return prefix+str1Middle+postfix;
		}else{
			return "";
		}
	}
	
	/**
	 * 单个文件
	 */
	public static void single(){
		logger.info("single-开始执行");
		
		fileRead(fileName1);
		containsCountGeshu(matchContent);
//		logger.info("1-->"+!fileName1.contains("add.jsp"));
//		logger.info("2-->"+!fileName1.contains("edit.jsp"));
//		logger.info("3-->"+!fileName1.contains("view.jsp"));
		
		if(printGeShu){
			logger.info("");
			logger.info("geshu 个数为："+geshu);
		}
		if(isDealFile){dealContent();}
		if(isWriteToFile){WriteStringToFile(fileName2);}
		
		logger.info("single-执行完毕");
	}
	
	
	/**
	 * 文件夹下的所有文件
	 * @throws IOException 
	 */
	public static void workPath() throws IOException{
		logger.info("workPath-开始执行");
    	File file = new File(filePath);
        FileUtils.getFiles(file);
        List<File> list = FileUtils.list;
        if(isPrintTsLog){
        	logger.info(""+list.size());
        }
        
        for(int i=0;i<list.size();i++){
        	File fileTemp = list.get(i);
    		geshu = 0;
    		fileName1 = fileTemp.getPath().replace("\\", "/");
        	fileRead(fileName1);
        	containsCountGeshu(matchContent);
        	
        	if(workType==workType_ALL_FILE ){
        		logger.info("");
    			logger.info((++fileCount)+"--fileName1-->"+fileName1);
    			logger.info("geshu 个数为："+geshu);
        	}else{
        		if(geshu>0){
        			if(workType==13 || workType==23 ){
                		logger.info("");
            			logger.info((++fileCount)+"--fileName1-->"+fileName1);
            			logger.info("geshu 个数为："+geshu);
                	}

            		fileName1 = fileTemp.getPath().replace("\\", "/");
    				if(isDealFile){dealContent();}
        			if(isWriteToFile){WriteStringToFile(fileTemp);}
            	}
        	}
        }
		
		logger.info("workPath-执行完毕");
	}
	
	public static void workPathEnd(){
		String var3 = getValueByPrefix(contentStr, "<script", "</script>");
		logger.info(var3);
	}
	
	public static void dealContent(){
		if(printGeShu){
			logger.info("");
			logger.info(++fileCount+"--geshu 个数为："+geshu);
		}
		for(int i=1;i<=geshu;i++){
			logger.info("");
			logger.info("	"+fileCount+"--fileName1-->"+fileName1);
			modifyCount++;
			logger.info("		整体--第"+modifyCount+"次");
			logger.info("		内部--共"+geshu+"次");
			logger.info("		内部--第"+i+"次");
			
			if(containsCount(matchContent)==0){
				errorSet.add("第"+i+"次，包含 0个  "+matchContent+"  "+fileName1);
				logger.info("第"+i+"次，包含 0个  "+matchContent+"  "+fileName1);
				break;
			}else if(containsCount(subStrPrefix)==0){
				errorSet.add("第"+i+"次，包含 0个  "+subStrPrefix+"  "+fileName1);
				logger.info("第"+i+"次，包含 0个  "+subStrPrefix+"  "+fileName1);
				break;
			}else if(containsCount(subStrPostfix)==0){
				errorSet.add("第"+i+"次，包含 0个  "+subStrPostfix+"  "+fileName1);
				logger.info("第"+i+"次，包含 0个  "+subStrPostfix+"  "+fileName1);
				break;
			}
			
			String strBefore = getContentBefore();
			String strMiddleTemp = getContentMiddle();
			String strAfter = getContentAfter(strBefore.length()+strMiddleTemp.length());
			
			String strMiddleDeal = "";
			//singleOrDouble = 1;			//1-single    2-double
			
			if(singleOrDouble==1){
				strMiddleDeal = getContentMiddleDeal01(strMiddleTemp);
			}
			
			if(!strMiddleDeal.equals("")){
				if(strMiddleDeal.equals("0001")){
					break;
				}else{
					contentStr = strBefore+strMiddleDeal+strAfter;
				}
			}
		}
	}
	
	
	/**
	 * 得到处理内容之前的内容
	 * @param content
	 * @return
	 */
	public static String getContentBefore(){
		//得到第一个matchContent的位置
		int index1 = contentStr.indexOf(matchContent);
		if(index1<0){
			return "";
		}
		//向前  截取字符串，获取最后一个div，即为上面matchContent所在的div
		String returnDealContent1 = contentStr.substring(0, index1);
		
		return returnDealContent1;
	}
	
	/**
	 * 得到处理内容之后的内容
	 * @param content
	 * @return
	 */
	public static String getContentAfter(){
		int index1 = contentStr.indexOf(subStrPostfix);
		if(index1<0){
			return "";
		}
		
		String returnDealContent1 = contentStr.substring(index1);
		returnDealContent1 = returnDealContent1.replaceFirst(subStrPostfix, "");
		returnDealContent1= returnDealContent1.replaceFirst("\n", "");
		
		return returnDealContent1;
	}
	
	public static String getContentAfter(int notAfterInt){
		return contentStr.substring(notAfterInt);
	}
	
	/**
	 * 得到处理内容
	 * @param content
	 * @return
	 */
	public static String getContentMiddle1(){
		String returnDealContent1 = "";
		if(contentStr.contains(subStrPrefix) && contentStr.contains(subStrPostfix) ){
			int index1 = contentStr.indexOf(subStrPrefix);
			int index2 = contentStr.indexOf(subStrPostfix);
			returnDealContent1 = contentStr.substring(index1,index2+subStrPostfix.length());
		}
		
		return returnDealContent1;
	}
	
	public static String getContentMiddle(){
		//得到第一个matchContent的位置
		int index1 = contentStr.indexOf(matchContent);
		//向前  截取字符串，获取最后一个div，即为上面matchContent所在的div
		String returnDealContent1 = contentStr.substring(index1);
		int index2 = returnDealContent1.indexOf(subStrPostfix);
		String returnDealContent2 = returnDealContent1.substring(0,index2+subStrPostfix.length());
		
		return returnDealContent2;
	}
	
	
	/**
	 * 获取文件里面的内容
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static void fileRead(String fileName) {
		try{
			File file = new File(fileName);//定义一个file对象，用来初始化FileReader
	        fileRead(file);
		}catch(Exception e){
			e.printStackTrace();
		}
    }
	
	
	/**
	 * 获取文件里面的内容
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static void fileRead(File file) {
		try{
	        FileReader reader = new FileReader(file);//定义一个fileReader对象，用来初始化BufferedReader
	        BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
	        StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
	        String s = "";
	        while ((s =bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
	            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
	        }
	        bReader.close();
	        contentStr = sb.toString();
		}catch(Exception e){
			e.printStackTrace();
		}
    }
	
	
	/**
	 * 将内容写入文件
	 * @param filePath
	 * @param content
	 */
	public static void WriteStringToFile(String filePath) {  
        File file = new File(filePath);  
        WriteStringToFile(file);
    }
	
	
	/**
	 * 将内容写入文件
	 * @param filePath
	 * @param content
	 */
	public static void WriteStringToFile(File file) {  
        try {  
            @SuppressWarnings("resource")
			PrintStream ps = new PrintStream(new FileOutputStream(file));  
            ps.println(contentStr);// 往文件里写入字符串  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
    }
	
	/**
	 * 字符串里面含有 字符串a的个数
	 * @param a
	 * @return
	 */
	public static int containsCount(String a) {
		return containsCount(contentStr,a);
	}
	
	/**
	 * 字符串里面含有 字符串a的个数
	 * @param a
	 * @return
	 */
	public static int containsCount(String aa, String a) {
		int counter = 0;
		for (int i = 0; i <= aa.length() - a.length(); i++) {
			String temp1 = aa.substring(i, i + a.length());
			if (temp1.equals(a)) {
				if(isPrintTsLog){
					logger.info("temp1-->"+temp1);
					logger.info("a-->"+a);
				}
				counter++;
			}
		}
		return counter;
	}
	
	/**
	 * 字符串里面含有 字符串a的个数
	 * @param a
	 * @return
	 */
	public static int containsCountGeshu(String a) {

		int counter = 0;
		for (int i = 0; i <= contentStr.length() - a.length(); i++) {
			String temp1 = contentStr.substring(i, i + a.length());
			if (temp1.equals(a)) {
				if(isPrintTsLog){
					System.out.println("temp1-->"+temp1);
					System.out.println("a-->"+a);
				}
				matchCount++;
				counter++;
			}
		}
		if(counter>0){
			if(singleOrDouble==1){
				geshu = counter;
			}else if(singleOrDouble==2){
				geshu = counter/2;
			}
		}
		
		return geshu;
	}

}

/*
crms-情况1-<div>前面有注释。
crms-qk1
<%--    <div>
        <label for="queryEntity_startTime">开始时间</label>
        <input type="text" name="queryEntity.startTimeStart" class="date"  onclick="WdatePicker({doubleCalendar:true})" />
        至
        <input type="text" name="queryEntity.startTimeEnd" class="date"  onclick="WdatePicker({doubleCalendar:true})" />
    </div>
    <div>
        <label for="queryEntity_endTime">结束时间</label>
        <input type="text" name="qqueryEntity.endTimeStart" class="date"  onclick="WdatePicker({doubleCalendar:true})" />
        至
        <input type="text" name="queryEntity.endTimeEnd" class="date"  onclick="WdatePicker({doubleCalendar:true})" />
    </div>--%>
 
 
 
 
 
 */

